# prompt: 生成一个脚本能批量获取daily bing的图片
#

import requests
import os
from datetime import datetime, timedelta

# 设置保存图片的目录
save_directory = "bing_images"
if not os.path.exists(save_directory):
    os.makedirs(save_directory)

def get_bing_image_url(date=None):
    """
    获取每日 Bing 图片的 URL。
    
    参数:
    date (str): 日期字符串，格式为 'YYYYMMDD'。如果为 None，则获取当天的图片。
    
    返回:
    str: 图片的 URL
    """
    base_url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx={}&n=1&mkt=en-US"
    if date is None:
        idx = 0
    else:
        today = datetime.strptime(date, "%Y%m%d")
        delta = (datetime.now() - today).days
        idx = delta

    response = requests.get(base_url.format(idx))
    data = response.json()
    image_url = f"https://cn.bing.com{data['images'][0]['url']}"
    return image_url

def download_and_save_image(url, save_path):
    """
    下载并保存图片。
    
    参数:
    url (str): 图片的 URL
    save_path (str): 保存图片的路径
    """
    response = requests.get(url)
    with open(save_path, "wb") as file:
        file.write(response.content)

def get_images_for_days(num_days=7):
    """
    获取过去 num_days 天的 Bing 图片。
    
    参数:
    num_days (int): 获取的天数，默认为 7 天
    """
    today = datetime.now()
    for i in range(num_days):
        date = (today - timedelta(days=i)).strftime("%Y%m%d")
        image_url = get_bing_image_url(date)
        image_filename = f"{date}.jpg"
        save_path = os.path.join(save_directory, image_filename)
        download_and_save_image(image_url, save_path)
        print(f"Downloaded {image_filename}")

if __name__ == "__main__":
    num_days = int(input("请输入要获取的天数（默认为 7 天）: "))
    get_images_for_days(num_days)